package com.ly.autosignin.common.utils;

import com.ly.autosignin.entity.Task;
import org.quartz.*;

public class ScheduleUtils {

    /**
     * 根据全限定名创建class对象
     * @param clazz
     * @return
     */
    @SuppressWarnings("unchecked")
    public static Class<? extends Job> createClass(String clazz) {
        try {
            return (Class<? extends Job>) Class.forName(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 创建一次计划
     * @param scheduler
     * @param task
     * @throws SchedulerException
     */
    public static void createSchedule(Scheduler scheduler, Task task) throws SchedulerException {
        String jobId=task.getJobId().toString();
        JobDetail jobDetail = JobBuilder.newJob(createClass(task.getInvokeTarget()))
                .withIdentity(jobId, task.getJobGroup())
                .build();

        CronTrigger cronTrigger = TriggerBuilder.newTrigger()
                .withIdentity(jobId, task.getJobGroup())
                .withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression()))
                .build();

        scheduler.scheduleJob(jobDetail,cronTrigger);
    }
}
